import sympy as sp
import numpy as np

def inverse_function_demo():
    print("=== 反函数求导直观演示 ===\n")
    
    # 示例1: 指数函数与对数函数（互为反函数）
    print("例1: 指数函数与对数函数的导数关系")
    x = sp.Symbol('x')
    y = sp.Symbol('y')
    
    # 原函数: y = e^x
    f = sp.exp(x)
    f_prime = sp.diff(f, x)
    print(f"指数函数: f(x) = e^x")
    print(f"指数函数的导数: f'(x) = {f_prime}")
    
    # 反函数: x = ln(y)
    # 根据反函数求导法则: g'(y) = 1 / f'(x) = 1 / e^x = 1/y
    g_prime_theoretical = 1 / y
    print(f"反函数（对数函数）的导数（理论）: g'(y) = 1/y")
    
    # 直接对反函数求导验证
    g = sp.log(y)
    g_prime_direct = sp.diff(g, y)
    print(f"反函数直接求导: g'(y) = {g_prime_direct}")
    print(f"理论值与直接求导一致: {g_prime_theoretical == g_prime_direct}\n")
    
    # 示例2: 平方函数与平方根函数（在限定定义域内）
    print("例2: 平方函数与平方根函数的导数关系（x ≥ 0）")
    
    # 原函数: y = x^2 (x ≥ 0)
    f_square = x**2
    f_square_prime = sp.diff(f_square, x)
    print(f"平方函数: f(x) = x²")
    print(f"平方函数的导数: f'(x) = {f_square_prime}")
    
    # 反函数: x = sqrt(y)
    # 根据反函数求导法则: g'(y) = 1 / f'(x) = 1 / (2x) = 1 / (2√y)
    g_sqrt_theoretical = 1 / (2 * sp.sqrt(y))
    print(f"反函数（平方根函数）的导数（理论）: g'(y) = 1/(2√y)")
    
    # 直接对反函数求导验证
    g_sqrt = sp.sqrt(y)
    g_sqrt_prime_direct = sp.diff(g_sqrt, y)
    print(f"反函数直接求导: g'(y) = {g_sqrt_prime_direct}")
    print(f"理论值与直接求导一致: {g_sqrt_theoretical == g_sqrt_prime_direct}\n")
    
    # 示例3: 三角函数与反三角函数
    print("例3: 正弦函数与反正弦函数的导数关系")
    
    # 原函数: y = sin(x), x ∈ [-π/2, π/2]
    f_sin = sp.sin(x)
    f_sin_prime = sp.diff(f_sin, x)
    print(f"正弦函数: f(x) = sin(x)")
    print(f"正弦函数的导数: f'(x) = {f_sin_prime}")
    
    # 反函数: x = arcsin(y)
    # 根据反函数求导法则: g'(y) = 1 / f'(x) = 1 / cos(x) = 1 / √(1 - sin²x) = 1 / √(1 - y²)
    g_arcsin_theoretical = 1 / sp.sqrt(1 - y**2)
    print(f"反函数（反正弦函数）的导数（理论）: g'(y) = 1/√(1 - y²)")
    
    # 直接对反函数求导验证
    g_arcsin = sp.asin(y)
    g_arcsin_prime_direct = sp.diff(g_arcsin, y)
    print(f"反函数直接求导: g'(y) = {g_arcsin_prime_direct}")
    print(f"理论值与直接求导一致: {g_arcsin_theoretical == g_arcsin_prime_direct}")

inverse_function_demo()